import getMongoConnect from './client.js';
import { ObjectID } from 'mongodb';

const collectionName = 'blog';
/**
 * 为对象添加属性
 * @param {*} obj
 * @param {*} key
 * @param {*} value
 * @return {*}
 */
function objectSetKey(obj, key, value) {
  obj && key ? (obj[key] = value || '') : null;
}

/**
 *  insert a blog
 * @param {} data
 */
async function insertOne(data) {
  const { db } = await getMongoConnect();

  const {
    title,
    description,
    user,
    type,
    state,
    sfiles,
    images,
    sfilesIcon,
  } = data;
  const result = await db.collection(collectionName).insertOne({
    title,
    description,
    type,
    state,
    sfiles,
    images,
    sfilesIcon,
    create_user: user,
    update_user: user,
    create_date: new Date(),
    update_date: new Date(),
  });
  console.debug(`blog insert one record ${result.acknowledged}. `);
  return result;
}

async function updateOne(data) {
  const { db } = await getMongoConnect();
  const { _id, user, sfiles, images, sfilesIcon } = data;
  const colect = {
    // sfiles: sfiles,
    // images: images,
    update_user: user,
    update_date: new Date(),
  };
  ['title', 'description', 'type', 'state'].forEach((key) => {
    objectSetKey(colect, key, data[key]);
  });
  if (sfiles && sfiles instanceof Array) {
    colect.sfiles = sfiles;
  }
  if (images && images instanceof Array) {
    colect.images = images;
  }
  if (sfilesIcon && sfilesIcon instanceof Array) {
    colect.sfilesIcon = sfilesIcon;
  }

  const result = await db
    .collection(collectionName)
    .updateOne({ _id: ObjectID(_id) }, [
      {
        $set: colect,
      },
    ]);

  console.debug(
    `blog update matchedCount ${result.matchedCount}, modifiedCount ${result.modifiedCount}. `
  );
  return result;
}

async function deleteOne({ _id }) {
  const { db } = await getMongoConnect();

  const result = await db
    .collection(collectionName)
    .deleteOne({ _id: { $eq: ObjectID(_id) } });

  console.debug(`blog is deleted count ${result.deletedCount}`);
  return result;
}

async function query(data) {
  const { db } = await getMongoConnect();

  const {
    type,
    state,
    title,
    sortField = 'update_date',
    order = -1,
    page = 1,
    pageSize = 10,
  } = data;
  const sortColumn = {};
  objectSetKey(sortColumn, sortField, order);

  const filters = [{}];
  if (type) {
    filters.push({ type: { $eq: type } });
  }
  if (state) {
    filters.push({ state: { $eq: state } });
  }
  if (title) {
    filters.push({ title: { $regex: new RegExp(`${title}`) } });
  }
  const result = await db
    .collection(collectionName)
    .find({
      $and: filters,
    })
    .project({
      images: 0,
      'sfiles.data': 0,
    })
    .limit(Number(pageSize))
    .skip((page - 1) * Number(pageSize))
    .sort(sortColumn)
    .toArray();
  return result;
}

async function queryOne({ _id }) {
  const { db } = await getMongoConnect();

  const result = await db
    .collection(collectionName)
    .findOne({ _id: { $eq: ObjectID(_id) } });
  return result;
}

async function queryAll(data) {
  const { db } = await getMongoConnect();

  const { type, state, title, sortField = 'update_date', order = -1 } = data;
  const sortColumn = {};
  objectSetKey(sortColumn, sortField, order);

  const filters = [{}];
  if (type) {
    filters.push({ type: { $eq: type } });
  }
  if (state) {
    filters.push({ state: { $eq: state } });
  }
  if (title) {
    filters.push({ title: { $regex: new RegExp(`${title}`) } });
  }
  const result = await db
    .collection(collectionName)
    .find({
      $and: filters,
    })
    .project({
      images: 0,
      'sfiles.data': 0,
    })
    .toArray();
  return result;
}

export { insertOne, deleteOne, updateOne, query, queryOne, queryAll };
